using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

/// <summary>
/// 游戏管理脚本
/// </summary>
public class GameManager : MonoBehaviour
{
    [Header("创建一个单例，方便其他脚本使用")]
    public static GameManager Instance;
    
    [Header("ui组件相关")]
    public Text scoreText;
    public Text overText;
    public GameObject gameOverPanel;
    public int score = 0;       //初始化score
    
    [Header("用场景中的敌人生成器")]
    public EnemySpawner spawner; 
    
    [Header("音频相关")]
    public List<AudioClip> audioClips = new List<AudioClip>();
    private AudioSource audioSource;
    
    void Awake()
    {
        // 这是让Instance生效的关键代码
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    /// <summary>
    /// 游戏初始化设置、音效和ui相关
    /// </summary>
    void Start()
    {
        gameOverPanel.SetActive(false); // 游戏开始时隐藏结束面板
        UpdateScoreText();
        audioSource = GetComponent<AudioSource>();
    }
    
    /// <summary>
    /// 游戏得分计算
    /// </summary>
    public void AddScore(int amount)
    {
        score += amount;
        UpdateScoreText();
    }

    /// <summary>
    /// 游戏得分UI
    /// </summary>
    void UpdateScoreText()
    {
        scoreText.text = "Score: " + score;
    }

    /// <summary>
    /// 游戏结束相关
    /// </summary>
    public void GameOver()
    {
        audioSource.PlayOneShot(audioClips[1]); // 在游戏结束时播放死亡音效
        gameOverPanel.SetActive(true);//显示面板
        //可以在这里加上 Time.timeScale = 0; 来暂停游戏
        overText.text = "最终得分: " + score;
        if (spawner != null)
        {
            spawner.StopSpawning();
        }

        // 让所有现存的敌人也停止移动
        GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
        foreach (GameObject enemy in enemies)
        {
            Destroy(enemy.GetComponent<EnemyController>()); // 销毁敌人的移动脚本
            Destroy(enemy.GetComponent<Rigidbody2D>()); // 销毁敌人的刚体，让它停在原地
        }
    }
    
    /// <summary>
    /// 重新开始游戏
    /// </summary>
    public void RestartGame()
    {
        // Time.timeScale = 1; // 如果暂停了游戏，要恢复
        SceneManager.LoadScene(SceneManager.GetActiveScene().name); // 重新加载当前场景
    }
    
    /// <summary>
    /// 播放失败音效
    /// </summary>
    public void PlayExplosionSound()
    {
        audioSource.PlayOneShot(audioClips[0]);
    }
    
    /// <summary>
    /// 退出游戏
    /// </summary>
    public void QuitGame()
    {
        // 在打包后的游戏中退出
        Application.Quit();
    }
}
